<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>user 100</title>
    <base>
    <script src="jquery.min.js"></script>
    <script src="socket.io.js"></script>
    <style>
        body {
            padding: 20px;
        }
        #console {
            height: 450px;
            overflow: auto;
        }
        .msg {
            color: orange;
        }
        .connect-msg {
            color: green;
        }
        .disconnect-msg {
            color: red;
        }
    </style>
</head>

<body>
    <div id="console" class="well"></div>
	
	<input id="userID" name="userID" placeholder="请输入用户ID">
	<input id="msgContent" name="msgContent" placeholder="请输入消息">
	<input type="button" onclick="sendMsg()" value="发送"/>
</body>


<script type="text/javascript">
    var socket;
    connect();

    function connect() {
        var userID = 100;
        var opts = {
            query: 'userID=' + userID
        };
        socket = io.connect('http://localhost:9092', opts);
        socket.on('connect', function () {
            console.log("连接成功");
            serverOutput('<span class="connect-msg">连接成功</span>');
        });
        socket.on('receiveMsg', function (data) {
            output('<span class="msg">' + data.msgContent + ' </span>');
            console.log(data);
        });

        socket.on('disconnect', function () {
            serverOutput('<span class="disconnect-msg">' + '已下线! </span>');
        });
    }
    
    function output(message) {
        var element = $("<div>" + " " + message + "</div>");
        $('#console').prepend(element);
    }

    function serverOutput(message) {
        var element = $("<div>" + message + "</div>");
        $('#console').prepend(element);
    }
	
	// 发送消息
	function sendMsg() {
		var userID = $.trim($("#userID").val());
		var msgContent = $.trim($("#msgContent").val());
		// 消息不能为空
		if (msgContent) {
			socket.emit('sendMsg', {
				"userID": userID,
				"msgContent": msgContent
			});
		} else {
			alert("消息不能为空");
		}
		$("#msgContent").val('');
		
	}
	


</script>
</html>

